package com.lihaogn.sell.web;


import com.lihaogn.sell.dto.WxOrderDetailDto;
import com.lihaogn.sell.dto.WxOrderDto;
import com.lihaogn.sell.dto.WxReviewDto;
import com.lihaogn.sell.entity.*;
import com.lihaogn.sell.service.OrderService;
import com.lihaogn.sell.service.ProductService;
import com.lihaogn.sell.service.UserService;
import com.lihaogn.sell.utils.HttpClientUtil;
import com.lihaogn.sell.vo.WeChatVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @FileName: WeChatController
 * @Description: 微信小程序数据接口
 * @Author: lihao
 * @Date: 2019-06-05 20:46
 * @Version: 1.0
 */
@Controller
@Api(tags = "微信小程序数据接口")
public class WeChatController {

    @Autowired
    private WeChatVo weChatVo;

    @Autowired
    ProductService productService;

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;


    /**
     * 登录接口
     *
     * @param code
     * @return
     */
    @PostMapping(value = "/weChatLogin")
    @ResponseBody
    private String weChatLogin(@RequestBody String code) {

        String appid = "你的appid";
        String secret = "你的secret";

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        String wxResult = HttpClientUtil.doGet(url);

        return wxResult;
    }

    /**
     * 获取轮播图url
     *
     * @return
     */
    @GetMapping(value = "/slideShow")
    @ResponseBody
    private WeChatVo carouselShow() {

        List<String> picNameList = new ArrayList<>();
//        picNameList.add("http://localhost/sell/carousel/liangbanhuanggua.png");
//        picNameList.add("http://localhost/sell/carousel/ganbianhuacai.png");
//        picNameList.add("http://localhost/sell/carousel/shiguobanfan.png");

        picNameList.add("https://www.lihaogn.top/sell/carousel/liangbanhuanggua.png");
        picNameList.add("https://www.lihaogn.top/sell/carousel/ganbianhuacai.png");
        picNameList.add("https://www.lihaogn.top/sell/carousel/shiguobanfan.png");

        weChatVo.setCode(200);
        weChatVo.setMsg("OK");
        weChatVo.setData(picNameList);

        return weChatVo;
    }

    /**
     * 获取所有food信息
     *
     * @return
     */
    @GetMapping(value = "/wGetAllFood")
    @ResponseBody
    private WeChatVo wGetAllFood() {

        weChatVo.setCode(200);
        weChatVo.setMsg("OK");
        weChatVo.setData(productService.getAllFood());

        return weChatVo;
    }

    /**
     * 获取推荐菜品
     * @param userId
     * @param peoples
     * @return
     */
    @GetMapping(value = "/wGetRecom")
    @ResponseBody
    private WeChatVo wGetRecom(String userId, Integer peoples) {

//        System.out.println("用餐人数：" + peoples);

        weChatVo.setCode(200);
        weChatVo.setMsg("OK");
        weChatVo.setData(productService.queryRecom(userId,peoples));

        return weChatVo;
    }

    /**
     * 接收订单
     *
     * @param wxOrderDto
     * @return
     */
    @PostMapping(value = "/wAddOrder")
    @ResponseBody
    private WeChatVo wAddOrder(@RequestBody WxOrderDto wxOrderDto) {

//        System.out.println(wxOrderDto);


        OrderDetail orderDetail = new OrderDetail();

        // 获取到orderId
        String wOrderId = wxOrderDto.getOrderId();
        // 如果wOrderId不为空，则说明是加菜
        if (wOrderId != "") {
            // 根据wOrderId添加detail
            for (WxOrderDetailDto item : wxOrderDto.getOrderData()) {
                // detail赋值
                orderDetail.setOrderItemId(UUID.randomUUID().toString());
                orderDetail.setOrderItemCount(item.getSellCount());
                orderDetail.setOrderItemCost(item.getItemCost());
                orderDetail.setFoodId(item.getFoodId());
                orderDetail.setOrderId(wOrderId);
                // 插入数据库
                int j = orderService.addOneOrderDetail(orderDetail);
                if (j != 1) {
                    weChatVo.setCode(0);
                    weChatVo.setMsg("数据库操作异常");
                    return weChatVo;
                }
            }

            weChatVo.setCode(1);
            weChatVo.setMsg("ok");
            weChatVo.setDataString(wOrderId);
            return weChatVo;
        }

//        ==================================================================
        // 获取用户信息
//        User user = wxOrderDto.getUserInfo();
//        String userId = user.getUserWxOpenid();
//        // 查询用户是否存在
//        int userNum = userService.getUserById(userId);
//        if (userNum != 1) {
//            // 用户不存在则新增一个用户
//            userService.addOneUser(user);
//        }

        // 修改用户信息，随机获取数据库中的用户，增加数据量使用
        List<User> users = userService.getAllUser();
        Random random = new Random();
        int index = random.nextInt(14);
        User tmpUser = users.get(index);
        wxOrderDto.setUserInfo(tmpUser);
        String userId = tmpUser.getUserWxOpenid();

//        ==================================================================

        Order order = new Order();
        // order实体赋值
        String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setOrderPeoples(wxOrderDto.getOrderPeoples());
        order.setOrderDeskId(wxOrderDto.getOrderDeskId());
        order.setOrderPayStatus(wxOrderDto.getOrderPayStatus());
        order.setOrderCost(wxOrderDto.getOrderCost());

        // 插入数据库
        int i = orderService.addOneOrder(order);

        if (i == 1) {
            // 插入成功，再插入详情
            for (WxOrderDetailDto item : wxOrderDto.getOrderData()) {
                // detail赋值
                orderDetail.setOrderItemId(UUID.randomUUID().toString());
                orderDetail.setOrderItemCount(item.getSellCount());
                orderDetail.setOrderItemCost(item.getItemCost());
                orderDetail.setFoodId(item.getFoodId());
                orderDetail.setOrderId(orderId);
                // 插入数据库
                int j = orderService.addOneOrderDetail(orderDetail);
                if (j != 1) {
                    weChatVo.setCode(0);
                    weChatVo.setMsg("数据库操作异常");
                    return weChatVo;
                }
            }

            weChatVo.setCode(1);
            weChatVo.setMsg("ok");
            weChatVo.setDataString(orderId);
            return weChatVo;
        }
        weChatVo.setCode(0);
        weChatVo.setMsg("异常");
        return weChatVo;
    }

    /**
     * 支付
     *
     * @param orderId
     * @return
     */
    @GetMapping(value = "/wPayOrder")
    @ResponseBody
    private Integer wPayOrder(String orderId) {
        return orderService.changeOrderPayStatus(orderId);
    }

    /**
     * 修改订单金额
     *
     * @param orderId
     * @param orderCost
     * @return
     */
    @GetMapping(value = "/wUpdateOrder")
    @ResponseBody
    private Integer wUpdateOrder(String orderId, Double orderCost) {

        return orderService.changeOrder(orderId, orderCost);
    }

    /**
     * 更新评分
     *
     * @param wxReviewDto
     * @return
     */
    @PostMapping(value = "/wUpdateOrderItemScore")
    @ResponseBody
    private Integer wUpdateOrderItemScore(@RequestBody WxReviewDto wxReviewDto) {

        System.out.println(wxReviewDto);
        HashMap<String, Object> reviewMap = new HashMap<>();
        reviewMap.put("orderId", wxReviewDto.getOrderId());
        for (ReviewData review : wxReviewDto.getReviewList()) {
            // 获取菜品评分
            Integer orderItemScore = review.getOrderItemScore();
            if (orderItemScore != null) {
                reviewMap.put("foodId", review.getFoodId());
                reviewMap.put("orderItemScore", orderItemScore);
                try {
                    orderService.updataOrderItemScore(reviewMap);
                } catch (Exception e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        }
        return 1;
    }


}
